package m.jclecai.com.activity;

import android.animation.ObjectAnimator;
import android.content.Intent;
import android.graphics.Color;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.squareup.okhttp.Request;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import m.jclecai.com.R;
import m.jclecai.com.base.BaseActivity;
import m.jclecai.com.bean.Response.ResponseSignList;
import m.jclecai.com.bean.UserBean;
import m.jclecai.com.bean.sign.ContinueSignBean;
import m.jclecai.com.bean.sign.DateBean;
import m.jclecai.com.constant.Constant_Url;
import m.jclecai.com.listener.Callback;
import m.jclecai.com.utils.PreferenceUtil;
import m.jclecai.com.utils.http.FastOk;
import m.jclecai.com.utils.http.HttpManager;
import m.jclecai.com.utils.http.responseBody.BaseBody;
import m.jclecai.com.view.AutoSwipeRefreshLayout;

public class SignActivity extends BaseActivity implements SwipeRefreshLayout.OnRefreshListener{

    @BindView(R.id.tv_my_gold_number)
    TextView mTvMyGoldNumber;
    @BindView(R.id.iv_sign)
    ImageView mIvSign;
    @BindView(R.id.ll_go_game_room)
    LinearLayout mLlGoGameRoom;
    @BindView(R.id.tv_continued_sign)
    TextView mTvContinuedSign;

    @BindView(R.id.ll_sign_rules)
    LinearLayout mLlSignRules;
    @BindView(R.id.rv_sign_reward)
    RecyclerView mRvSignReward;
    @BindView(R.id.tv_date)
    TextView mTvDate;
    @BindView(R.id.rv_calendar)
    RecyclerView mRvCalendar;

    @BindView(R.id.rl_refresh_layout)
    AutoSwipeRefreshLayout mRlRefreshLayout;

    public List<ContinueSignBean> mContinueSignList = new ArrayList<>();
    public List<DateBean> mCalendarList = new ArrayList<>();

    private UserBean mUserBean;
    private CalenderAdapeter mCalenderAdapeter;
    private AlertDialog mSignRewardDialog;
    private TextView mTvSignRewardDialogGoldNumber;
    private View mRuleView;

    @Override
    protected int getContentView() {
        return R.layout.activity_sign;
    }

    @Override
    protected void initView() {
        setTitle("每日签到");
        leftOptionText("");

        mRvSignReward.setLayoutManager(new GridLayoutManager(this, 3) {
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        });

        mRvCalendar.setLayoutManager(new GridLayoutManager(this, 7) {
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        });
        initDialog();
    }

    private void initDialog() {
        //这里有很多的对话框；签到成功的对话框，领取签到奖励的对话框；
        mRlRefreshLayout.setOnRefreshListener(this);
        mRlRefreshLayout.setRefreshing(true);
        initRulesDialog();
        initSignRewardDialog();
    }

    //这里其实是一个就是一个View
    private void initRulesDialog() {
        //这里的话，我们要做的一个操作就是显示一个全屏的popupWindow;
        mRuleView = View.inflate(this, R.layout.popup_sign_rule, null);

        activityBase.addView(mRuleView, activityBase.getChildCount());

        mRuleView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                mRuleView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                mRuleView.setTranslationY(-mRuleView.getHeight());
            }
        });
        mRuleView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                closeRulesAnimation();
            }
        });
    }

    private void OpenRulesAnimation() {
        ObjectAnimator.ofFloat(mRuleView, "TranslationY", -mRuleView.getHeight(), 0).setDuration(500).start();
    }

    private void closeRulesAnimation() {
        ObjectAnimator.ofFloat(mRuleView, "TranslationY", 0, -mRuleView.getHeight()).setDuration(500).start();
    }


    private void initSignRewardDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setCancelable(false);
        View view = View.inflate(this, R.layout.dialog_sign_reward, null);
        mTvSignRewardDialogGoldNumber = ((TextView) view.findViewById(R.id.tv_gold_number));
        view.findViewById(R.id.tv_sure).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mSignRewardDialog.dismiss();
            }
        });
        builder.setView(view);
        mSignRewardDialog = builder.create();
    }

    @Override
    protected void initData() {
        initUser();
        //初始化连续签到奖励
        initContinuedSignReward();
        //初始化日历；
        initCalendar();
        //请求网络获取数据；
        requestGold();
    }

    private void initUser() {
        mUserBean = PreferenceUtil.readUser(this);

    }

    private void initCalendar() {
        initCalendarData();
        mCalenderAdapeter = new CalenderAdapeter(mCalendarList);
        mRvCalendar.setAdapter(mCalenderAdapeter);
    }

    private void initContinuedSignReward() {
        initContineSignData();
        mRvSignReward.setAdapter(new MyRewardAdapter());
    }

    //查询自己的金币
    private void requestGold() {

        String userName = PreferenceUtil.getUserName(this);
        String password = PreferenceUtil.getPassword(this);
        HashMap<String, String> pair = new HashMap<>();
        pair.put("user", userName);
        pair.put("password", password);
        HttpManager.postAsyn(Constant_Url.SIGN_LIST, new HttpManager.StringCallback() {
            @Override
            public void onFailure(Request request, IOException e) {
                if (mRlRefreshLayout != null)
                    mRlRefreshLayout.setRefreshing(false);
                DisPlay("请检查网络！！！");
            }

            @Override
            public void onResponse(String response) {
               if (mRlRefreshLayout != null)
                   mRlRefreshLayout.setRefreshing(false);

                try {
                    if(!TextUtils.isEmpty(response)){

                        ResponseSignList responseSignList = FastOk.get(response, ResponseSignList.class);

                        if (responseSignList != null) {

                            if ("0".equals(responseSignList.getStatus())) {
                                //这里我们要做的一个操作就是更新列表签到的列表；
                                updateSignList(responseSignList);
                            }else {
                                DisPlay(responseSignList.getMessage());
                            }
                        }else{
                            DisPlay("网络异常！");
                        }
                    }else{
                        DisPlay("网络异常！");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    DisPlay("网络异常！");
                }
            }
        }, pair);

    }

    @OnClick({R.id.tv_my,R.id.tv_my_gold_number})
    public void onClickMoney(){
        //这里表示我的金币
        startActivity(GoldManagerActivity.getGoldManagerIntent(this,true));
    }

    /**
     * 这里我们要做的一个操作就是更新日历上的显示
     *
     * @param responseSignList
     */
    private void updateSignList(ResponseSignList responseSignList) {
        //这里是头部，我的金币和是否可以签到；
        mTvMyGoldNumber.setText(TextUtils.isEmpty(responseSignList.getGoldcoin())?"0":responseSignList.getGoldcoin());
        //这里的话，我们是需要更新日历的；但是这里我们暂时先不做；
        List<String> records = responseSignList.getRecords();
        //从这里我们是需要判断一下是否包括的有今天，
        // 如果没有的话，我们可以签到的，如果有的话，我们是不能签到的；
        Calendar instance = Calendar.getInstance();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String today = simpleDateFormat.format(instance.getTime());
        if (records.contains(today)) {
            //这里我们是可以可以签到的；
            mIvSign.setEnabled(false);
        } else {
            mIvSign.setEnabled(true);
        }

        //这里的话，我们是需要刷新日历上面的显示的内容的；
        mCalenderAdapeter.refreshDate(responseSignList.getRecords());
        mTvContinuedSign.setText("本月已签到" + responseSignList.getRecords().size() + "天");
    }

    @Override
    protected void initListener() {
        mIvSign.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //请求网络；进行一个签到；
                if (isLogin()) {
                    String userName = PreferenceUtil.getUserName(SignActivity.this);
                    String password = PreferenceUtil.getPassword(SignActivity.this);
                    HashMap<String, String> pair = new HashMap<>();
                    pair.put("user", userName);
                    pair.put("password", password);
                    HttpManager.postAsyn(Constant_Url.SIGN, new HttpManager.StringCallback() {
                        @Override
                        public void onFailure(Request request, IOException e) {
                            DisPlay("请检查网络！！！");
                        }

                        @Override
                        public void onResponse(String response) {
                            //这里我们对其进一个判断；
                            System.out.println(response);
                            BaseBody body = FastOk.get(response, BaseBody.class);
                            if (body.getStatus() == 0) {
                                //这里表示成功；
                                requestGold();
                            } else {
                                //已经签到过了，签到失败；
                                DisPlay("签到失败！！！");
                            }
                        }
                    }, pair);
                }else{
                    checkLogin(new Callback(){

                        @Override
                        public void callbackSuccess() {
                            //登陆成功，我们是需要判断一下；
                            requestGold();
                        }
                    });
                }
            }
        });

        mLlSignRules.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                OpenRulesAnimation();
            }
        });

        mLlGoGameRoom.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //这里我们要执行的是跳转到娱乐厅里面；
                startActivity(new Intent(SignActivity.this, GameRoomActivity.class));
            }
        });
    }

    @Override
    public void onRefresh() {
        requestGold();
    }


    public class MyRewardAdapter extends RecyclerView.Adapter<ContinueSignViewHolder> {


        @Override
        public ContinueSignViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

            View view = View.inflate(SignActivity.this, R.layout.item_continued_sign, null);
            return new ContinueSignViewHolder(view);
        }

        @Override
        public void onBindViewHolder(ContinueSignViewHolder holder, int position) {
            ContinueSignBean continueSignBean = mContinueSignList.get(position);

            holder.mTvContinuedDate.setText(continueSignBean.getContinueDate());
            holder.mTvContinuedReward.setText(continueSignBean.getContinueReward());
        }

        @Override
        public int getItemCount() {
            return mContinueSignList.size();
        }
    }

    //连续签到的ViewHolder
    public class ContinueSignViewHolder extends RecyclerView.ViewHolder {


        @BindView(R.id.tv_continued_date)
        TextView mTvContinuedDate;
        @BindView(R.id.tv_continued_reward)
        TextView mTvContinuedReward;
        @BindView(R.id.tv_get_continued_ward)
        TextView mTvGetContinuedWard;

        public ContinueSignViewHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);

            mTvGetContinuedWard.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    final int type = getLayoutPosition();

                    String userName = PreferenceUtil.getUserName(SignActivity.this);
                    String password = PreferenceUtil.getPassword(SignActivity.this);
                    HashMap<String, String> pair = new HashMap<>();
                    pair.put("user", userName);
                    pair.put("password", password);
                    pair.put("type", type + "");

                    HttpManager.postAsyn(Constant_Url.SIGN_REWARD, new HttpManager.StringCallback() {
                        @Override
                        public void onFailure(Request request, IOException e) {
                            DisPlay("请检查网络！！！");
                        }

                        @Override
                        public void onResponse(String response) {
                            System.out.println(response);
                            try {
                                BaseBody body = FastOk.get(response, BaseBody.class);
                                if(body!=null){

                                    if (body.getStatus() == 0) {
                                        //这里我们能弹出签到成功的对话框
                                        if (type == 0) {
                                            mTvSignRewardDialogGoldNumber.setText("20金币");
                                        } else if (type == 1) {
                                            mTvSignRewardDialogGoldNumber.setText("50金币");
                                        } else if (type == 2) {
                                            mTvSignRewardDialogGoldNumber.setText("100金币");
                                        }
                                        mSignRewardDialog.show();
                                    } else {
                                        //这里我们弹出获取失败的对话框
                                        DisPlay(body.getMessage());
                                    }

                                }else{
                                    DisPlay("网络异常！！！");
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                                DisPlay("网络异常！！！");
                            }
                        }
                    }, pair);
                }
            });
        }
    }

    public void initContineSignData() {

        ContinueSignBean continueSignBean0 = new ContinueSignBean();
        continueSignBean0.setContinueSignId(0);
        continueSignBean0.setContinueDate("连续3天");
        continueSignBean0.setContinueReward("20金币");
        mContinueSignList.add(continueSignBean0);

        ContinueSignBean continueSignBean1 = new ContinueSignBean();
        continueSignBean1.setContinueSignId(1);
        continueSignBean1.setContinueDate("连续14天");
        continueSignBean1.setContinueReward("50金币");
        mContinueSignList.add(continueSignBean1);


        ContinueSignBean continueSignBean2 = new ContinueSignBean();
        continueSignBean2.setContinueSignId(2);
        continueSignBean2.setContinueDate("连续28天");
        continueSignBean2.setContinueReward("100金币");
        mContinueSignList.add(continueSignBean2);
    }


    //calendar的一个adapter；
    public class CalenderAdapeter extends RecyclerView.Adapter<CalendarViewHolder> {

        public List<DateBean> mDateBeanList = new ArrayList<>();

        public CalenderAdapeter(List<DateBean> dateBeanList) {
            mDateBeanList = dateBeanList;
        }

        //这里的这个方法的意思是：刷新显示已经签到的日期；
        public void refreshDate(List<String> mlist) {

            for (String dateString : mlist) {

                for (int i = 0; i < mDateBeanList.size(); i++) {
                    DateBean dateBean = mDateBeanList.get(i);
                    Date date = dateBean.getDate();
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                    String format = simpleDateFormat.format(date);
                    //如果当前已经签到过了，我们就修改界面；
                    if (format.equals(dateString)) {
                        dateBean.setSigned(true);
                        notifyItemChanged(i);
                    }
                }
            }
        }

        @Override
        public CalendarViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View inflate = View.inflate(SignActivity.this, R.layout.item_calendar, null);
            return new CalendarViewHolder(inflate);
        }

        @Override
        public void onBindViewHolder(CalendarViewHolder holder, int position) {

            DateBean dateBean = mDateBeanList.get(position);

            if (dateBean.isSigned) {
                //是否签到了
                holder.mFlBg.setVisibility(View.VISIBLE);

            } else {
                holder.mFlBg.setVisibility(View.INVISIBLE);
            }

            if (dateBean.isToday()) {
                holder.mTvReward.setText("今天");
            } else {
                holder.mTvReward.setText("");
            }

            if (dateBean.isCurrentMonth) {
                holder.mTvDate.setTextColor(Color.DKGRAY);

            } else {
                holder.mTvDate.setTextColor(Color.GREEN);
            }

            holder.mTvDate.setText(dateBean.getDateString());

            //只显示本月的
            if (dateBean.isCurrentMonth) {
                holder.itemView.setVisibility(View.VISIBLE);
            } else {
                holder.itemView.setVisibility(View.INVISIBLE);
            }
        }

        @Override
        public int getItemCount() {
            return mDateBeanList.size();
        }
    }


    //日历的ViewHolder的实现；
    public class CalendarViewHolder extends RecyclerView.ViewHolder {


        @BindView(R.id.fl_bg)
        FrameLayout mFlBg;
        @BindView(R.id.tv_date)
        TextView mTvDate;
        @BindView(R.id.tv_reward)
        TextView mTvReward;

        public CalendarViewHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }
    }


    //对日历进行一个初始化操作；
    private void initCalendarData() {
        List<Integer> mLastMonthDays = new ArrayList<>();

        //这里我们是需要将日期先获取得到；
        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH);

        mTvDate.setText(year + "年" + (month + 1) + "月");

        int monthOfDay = calendar.get(Calendar.DAY_OF_MONTH);

        calendar.set(year, month, 1);
        int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK); //1的话，表示上个月没有一天是在这里的，表示周末，2表示周一，上个月有一天
        //这里我们获取得到星期几
        int lastMonthDays = getMonthDays(year, month - 1);  //上个月有多少天；
        int monthDays = getMonthDays(year, month);          //这个月有多少天

        for (int i = dayOfWeek - 1; i > 0; i--) {
            int lastDay = lastMonthDays - i + 1;        //本页面显示上个月的天数
            mLastMonthDays.add(lastDay);

            Calendar instance = Calendar.getInstance();
            instance.set(year, month - 1, lastDay);

            //将数据进行一个封装；
            DateBean dateBean = new DateBean();
            dateBean.setSigned(false);
            dateBean.setDate(instance.getTime());
            dateBean.setDateString(lastDay + "");

            dateBean.setCurrentMonth(false);
            mCalendarList.add(dateBean);
        }

        for (int i = 0; i < monthDays; i++) {   //本页面显示这个月的天数
            //这里我们是将剩余的空位加在这个月；
            int day = i + 1;
            if (day <= monthDays) {

                Calendar instance = Calendar.getInstance();
                instance.set(year, month, day);
                //将数据进行一个封装；
                DateBean dateBean = new DateBean();
                //  这里是判断今天的代码实现；
                if (day == monthOfDay) {
                    dateBean.setToday(true);
                } else {
                    dateBean.setToday(false);
                }
                dateBean.setDate(instance.getTime());
                dateBean.setDateString(day + "");
                dateBean.setCurrentMonth(true);

                mCalendarList.add(dateBean);
            } else {
                break;
            }
        }
        //==通过下面的代码我们可以轻松的实现上一个月和下一个月的界面的显示；==
        /*for (int i = 0; i < 35 - mLastMonthDays.size(); i++) {   //本页面显示这个月的天数
            //这里我们是将剩余的空位加在这个月；
            int day = i + 1;
            if (day < monthDays) {

                Calendar instance = Calendar.getInstance();
                instance.set(year,month,day);
                //将数据进行一个封装；
                DateBean dateBean = new DateBean();
                if(day==monthOfDay){
                    dateBean.setSigned(true);
                }else{
                    dateBean.setSigned(false);
                }
                dateBean.setDate(instance.getTime());
                dateBean.setDateString(day+"");
                dateBean.setCurrentMonth(true);

                mCalendarList.add(dateBean);
            } else {
                break;
            }
        }*/

       /* //本页面显示下个月的天数；
        if (mCalendarList.size() < 35) {
            //这里我们要添加下个月的天数；
            int addDataNumber = 35 - mCalendarList.size();     //下个月需要显示的天数
            for (int i = 0; i < addDataNumber; i++) {
                int day = i + 1;        //从1开始加

                Calendar instance = Calendar.getInstance();
                instance.set(year,month,day);
                //将数据进行一个封装；
                DateBean dateBean = new DateBean();
                dateBean.setSigned(false);
                dateBean.setDate(instance.getTime());
                dateBean.setDateString(i+"");
                dateBean.setCurrentMonth(false);

                mCalendarList.add(dateBean);
            }
        }*/
    }


    /**
     * 获取每个月有多少天；
     *
     * @param year  那一年
     * @param month 哪个月
     * @return 这个月有多少天；
     */
    public static int getMonthDays(int year, int month) {
        month++;
        switch (month) {
            case 1:
            case 3:
            case 5:
            case 7:
            case 8:
            case 10:
            case 12:
                return 31;
            case 4:
            case 6:
            case 9:
            case 11:
                return 30;
            case 2:
                if (((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0)) {
                    return 29;
                } else {
                    return 28;
                }
            default:
                return -1;
        }
    }
}
